<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="客户经理" prop="inviteId">
        <el-select v-model="queryParams.inviteId" clearable placeholder="请选择客户经理" class="menu_option">
          <el-option
            v-for="item in allSite"
            :label="item.sitename+'-'+item.customerName"
            :value="item.id"
            :key="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="手机号" prop="mobile">
        <el-input
          v-model="queryParams.mobile"
          placeholder="请输入手机号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon icon="ep:search" class="mr-5px" />
          搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon icon="ep:refresh" class="mr-5px" />
          重置
        </el-button>
<!--        <el-button-->
<!--          type="primary"-->
<!--          plain-->
<!--          @click="openForm('create')"-->
<!--          v-hasPermi="['bank:coupon-user:create']"-->
<!--        >-->
<!--          <Icon icon="ep:plus" class="mr-5px" />-->
<!--          新增-->
<!--        </el-button>-->
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['bank:coupon-user:export']"
        >
          <Icon icon="ep:download" class="mr-5px" />
          导出
        </el-button>
<!--        <el-button type="warning" plain @click="handleImport">-->
<!--          <Icon icon="ep:upload" />-->
<!--          导入-->
<!--        </el-button>-->
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <el-table-column label="编号" align="center" prop="id" width="150px" />
      <el-table-column label="客户经理" align="center" prop="inviteId" width="250px">
        <template #default="scope">
          <span>{{ `${allSiteMap[scope.row.inviteId].sitename}-${allSiteMap[scope.row.inviteId].customerName}` }}</span>
        </template>
      </el-table-column>
      <el-table-column label="手机号" align="center" prop="mobile" width="150px" />
      <el-table-column label="支付宝账户" align="center" prop="alipayAccount" width="250px" />
      <el-table-column label="已领" align="center" prop="alipayAccount" width="250px">
        <template #default="scope">
          <span>{{ parseCodeMoney(scope.row.qrcode) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="操作" align="center" width="150px">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['bank:coupon-user:update']"
          >
            编辑
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['bank:coupon-user:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <CouponUserForm ref="formRef" @success="getList" />

  <!-- 用户导入对话框 -->
  <CouponUserImportForm ref="importFormRef" @success="importSuccAfter" />
</template>

<script lang="ts" setup>
import { dateFormatter } from "@/utils/formatTime";
import download from "@/utils/download";
import * as CouponUserApi from "@/api/coupon/user";
import CouponUserForm from "./CouponUserForm.vue";
import CouponUserImportForm from "./CouponUserImportForm.vue";
import { useClipboard } from "@vueuse/core";

defineOptions({ name: "CouponUser" });

const message = useMessage(); // 消息弹窗
const { t } = useI18n(); // 国际化

const loading = ref(true); // 列表的加载中
const total = ref(0); // 列表的总页数
const list = ref([]); // 列表的数据
const allSite = ref([]);
const allSiteMap = ref({});
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  inviteId: null,
  mobile: null,
  verifyStatus: null,
  writeOffStatus: null,
  qrcode: null,
  registerIp: null,
  loginIp: null,
  loginDate: [],
  nickname: null,
  name: null,
  sex: null,
  mark: null,
  createTime: []
});
const queryFormRef = ref(); // 搜索的表单
const exportLoading = ref(false); // 导出的加载中

/** 查询列表 */
const getList = async () => {
  loading.value = true;
  try {
    const data = await CouponUserApi.getCouponUserPage(queryParams);
    list.value = data.list;
    total.value = data.total;
  } finally {
    loading.value = false;
  }
};

const getAllSite = async () => {
  try {
    const _allSite = await CouponUserApi.getAllSite();
    allSite.value = _allSite
    _allSite.forEach(item => {
      allSiteMap.value[item.id] = item
    })

    console.log(allSite.value)
    console.log(allSiteMap.value)
  } finally {

  }
}

const parseCodeMoney = (qrcode) => {
  let split = qrcode.split(",");
  let arr = { "54": "10元", "55": "50元", "56": "20元" };
  let list = [];
  split.forEach(item => {
    list.push(arr[item*1]);
  });
  return list.join(",");
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields();
  handleQuery();
};

/** 添加/修改操作 */
const formRef = ref();
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id);
};

/** 用户导入 */
const importFormRef = ref();
const handleImport = () => {
  importFormRef.value.open();
};

const importSuccAfter = () => {
  importFormRef.value.close();
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm();
    // 发起删除
    await CouponUserApi.deleteCouponUser(id);
    message.success(t("common.delSuccess"));
    // 刷新列表
    await getList();
  } catch {
  }
};

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm();
    // 发起导出
    exportLoading.value = true;
    const data = await CouponUserApi.exportCouponUser(queryParams);
    download.excel(data, "优惠券用户.xls");
  } catch {
  } finally {
    exportLoading.value = false;
  }
};

const copy = async (text: string) => {
  const { copy, copied, isSupported } = useClipboard({ source: text });
  if (!isSupported) {
    message.error(t("common.copyError"));
    return;
  }
  await copy();
  if (unref(copied)) {
    message.success(t("common.copySuccess"));
  }
};

const clipboardSuccess = () => {
  message.success('复制成功')
}

/** 初始化 **/
onMounted(() => {
  getAllSite();
  getList();
});
</script>
